package springboot.example.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springboot.example.springboot.common.BaseController;
import springboot.example.springboot.entity.UserInfo;
import springboot.example.springboot.service.UserInfoService;
import springboot.example.springboot.shiro.CryptographyUtil;
import springboot.example.springboot.tools.MyExecption;

import javax.annotation.Resource;

@Controller
public class LoginController extends BaseController {
    @Resource
    private UserInfoService userInfoService;

    @GetMapping("/login")
    public String loginG(){
        return "system/login";
    }

    @GetMapping("/register")
    public String registerG(){
        return "system/register";
    }

    @PostMapping("register")
    public String register(UserInfo user, Model model){

        try {
            userInfoService.save(user);
        } catch (MyExecption myExecption) {
            model.addAttribute("msg",myExecption.getMessage());
            return "system/register";
        }

        return "system/login";
    }

    @PostMapping("/login")
    public String login(UserInfo user,Model model) {

        // 此方法不处理登录成功,由shiro进行处理
        try {
            String password = CryptographyUtil.md5(user.getUsername(), user.getPassword());
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), password);
            token.setRememberMe(true);
            SecurityUtils.getSubject().login(token);
            return "system/index";
        } catch (Exception e) {
            model.addAttribute("msg", "账号或密码错误。");
            return "system/login";
        }
    }

    @RequestMapping("/index")
    public String index(){
        return "/system/index";
    }

    @RequiresRoles(value={"admin"})
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "I have admin quanxian";
    }


    @RequiresPermissions(value={"admin"})
                @RequestMapping("/permission")
    @ResponseBody
    public String permission(){
        return "I have admin quanxian";
    }

}

